// components/tag_expand_selector/tag_expand_selector.js
var util = require('../../utils/util.js')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    apiType: {
      type: String,
      value: '2'
    },
    showPre: {
      type: Boolean,
      value: !1
    },
    buttonTitle: {
      type: String,
      value: '开始匹配'
    },
    cutsomTag: {
      type: String,
      value: '',
      observer: function (newVal, oldVal, changedPath) {
        if (newVal.trim() != oldVal.trim()) {
          const result = this.addTag(newVal)
          if (!result) {
            wx.showToast({
              title: '添加失败,请检查标签是否已存在',
              icon: 'none',
              duration: 2000,
              complete: () => {
                wx.hideToast()
              }
            })
          } else {
            wx.showToast({
              title: '添加成功',
              duration: 2000,
              complete: () => {
              }
            })
          }
        }
      }
    },
    initTagSelectedArray: {
      type: Array,
      value: []
    },
    initCustomTagSelectedArray: {
      type: Array,
      value: []
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataSource: [],
    item_expand_ctl_List: [!1, !1],//子分类面板展开或者收缩状态控制
    item_select_index:-1,         //当前选中的大分类在数组中的索引
    current_item:[],              //当前展开的分类的子分类数组
    // custom_tag_array: [{ 'value': 'dd', 'selected': !0 }, { 'value': 'dd', 'selected': !1 }],
    custom_tag_array: [],

  },
  ready: function () {
    util.getKeyWord(this.properties.apiType == '2' ? { 'param':'lables' } : { 'type':'matching' },this.getkeyWordDidResponse, this.requestDidFaild,this)
    // util.getKeyWord.call(this, this.getkeyWordDidResponse, this.getkeyWordDidResponse)

  },

  /**
   * 组件的方法列表
   */
  methods: {
    addBtnClick: function(e) {
      this.triggerEvent('customTagDidClick', {}, {})
    },
    nextBtnClick: function (e) {
      this.combineResult()
    },
    goPrePage: function (e) {
      this.triggerEvent('goPre', {}, {})
    },
    itemDidTaped: function (e) {
      var tapIndex = e.target.dataset.index,d=this.data
      //计算将要展开的子类面板的索引
      var sub_item_pageno = parseInt(tapIndex / 3);
      //计算当前展开的子类面板索引
      var old_item_pageno = -1

      if ( d.item_select_index != -1 ) {
        old_item_pageno = parseInt(d.item_select_index / 3);
      }
      //点击的和之前点击的是同一个，取反控制面板的值
      if ( tapIndex == d.item_select_index ) {
        d.item_expand_ctl_List[sub_item_pageno] = !d.item_expand_ctl_List[sub_item_pageno]
        d.item_expand_ctl_List[sub_item_pageno] == !0 ? d.dataSource[d.item_select_index].selected = !0 : d.dataSource[d.item_select_index].selected = !1
        this.setData({
          item_expand_ctl_List: d.item_expand_ctl_List,
          dataSource: d.dataSource
        })
        return
      }       
       //不是同一个
       //之前有打开的先关闭
      if (d.item_select_index != -1) {
        d.item_expand_ctl_List[old_item_pageno] = !1
        d.dataSource[d.item_select_index].selected = !1
      }
      //打开新的
      d.item_expand_ctl_List[sub_item_pageno] = !0
      d.item_select_index = tapIndex
      d.dataSource[d.item_select_index].selected = !0
      this.setData({
        item_expand_ctl_List: d.item_expand_ctl_List,
        dataSource: d.dataSource,
        current_item: d.dataSource[d.item_select_index].results
      })
    },
    subItemDidTaped : function (e) {
      var tapIndex = e.target.dataset.index, d = this.data
      this.data.current_item[tapIndex].selected = !this.data.current_item[tapIndex].selected
      this.setData({
        current_item: d.dataSource[d.item_select_index].results
      })
      //遍历当前分类，设置当前分类下是否有子标签被选中的状态
      d.dataSource[d.item_select_index].has_subitem_selected = !1
      for (var i = 0; i < d.current_item.length; i++) {
        var one = d.current_item[i]
        if ( one.selected ) {
          d.dataSource[d.item_select_index].has_subitem_selected = !0
          break
        }
      }
    },
    customItemDidTaped : function (e) {
      var tapIndex = e.target.dataset.index, d = this.data
      this.data.custom_tag_array[tapIndex].selected = !this.data.custom_tag_array[tapIndex].selected
      this.setData({
        custom_tag_array: d.custom_tag_array
      })
    },
    nextBtnClick: function (e) {
      this.combineResult()
    },
    addSelectProperty : function (data) {
      var pages = data.map(
         (e,index) => {
          e.selected = !1
          e.has_subitem_selected = !1
          e.results.map(
            (el) => {
              el.selected = !1
            }
          )
           return parseInt(index/3)
         }
       )
      var pagesArray = [...new Set(pages)].map(
        (e) => {
          return !1
        }
      )
      this.data.dataSource = data;
      //如果有初始化选中的标签，则先处理这些标签
      if ( this.data.initTagSelectedArray.length > 0 ) {
         this.data.initTagSelectedArray.map(
           (id) => {
              this.data.dataSource.map(
                (e) => {
                  e.results.map(
                    (ie) => {
                      if (ie.id == id) {
                        ie.selected = !0
                        e.has_subitem_selected = !0
                      }
                    }
                  )
                }
              )
           }
         )
      }
      //如果有初始化的自定义标签，则先处理这些自定义的标签
      if ( this.data.initCustomTagSelectedArray.length > 0 ) {
        this.data.custom_tag_array = []
        this.data.initCustomTagSelectedArray.map(
          (e) => {
            var obj = {}
            obj.value = e
            obj.selected = !0
            this.data.custom_tag_array.push(obj)
          }
        )
        this.setData({
          custom_tag_array: this.data.custom_tag_array,
        })
      }
      this.setData({
        dataSource: this.data.dataSource,
        item_expand_ctl_List: pagesArray
      })
    },
    getkeyWordDidResponse: function (res) {
      console.log('did receive response tag: ' + res)
      console.log(res.data.result)
      console.log(this)

      this.addSelectProperty(res.data.result)
      // if (res.status == '200') {
      //   _this.setData({
      //     dataSource: res.data.result
      //   })
      //   _this.refreshData()
      // }
    },
    addTag: function(tag) {
      console.log(tag)
      var index = this.data.custom_tag_array.indexOf(tag)
      if (index == -1) {
        var data = {}
        data.value = tag
        data.selected = !0
        this.data.custom_tag_array.push(data)
        this.setData({
          custom_tag_array: this.data.custom_tag_array,
        })
        return true
      } else {
        return false
      }
    },
    combineResult : function (e) {
      var result = []
      this.data.dataSource.map(
         (e) => {
           e.results.map(
             (se) => {
               se.selected ?  result.push(se.id) :  !1
             }
           )
         }
      )
      if (result.length == 0) {
        wx.showToast({
          title: '请选择至少一个非自定义标签',
          icon: 'none'
        })
        return
      }
      var customResut = []
      this.data.custom_tag_array.map(
        (e) => {
          e.selected ? customResut.push(e.value) : !1
        }
      )
      console.log(customResut)
      this.triggerEvent('tagSelectedFinishedHandle', { 'tagSelectedArray': result, 'customTagSelectedArray': customResut}, {})
    }
  }
})
